package com.czk.netty.netty.tcp.protocaltcp.practice.server;

import com.czk.netty.netty.tcp.protocaltcp.practice.protocol.TransferProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/6/8 11:02
 */
public class ServerHandler extends SimpleChannelInboundHandler<TransferProtocol> {
    /**
     * 统计接收次数
     */
    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TransferProtocol transferProtocol) throws Exception {
        // 校验参数
        if (transferProtocol == null) {
            throw new RuntimeException("数据传输错误");
        }
        // 拿到长度
        int length = transferProtocol.getLength();
        // 拿到内容
        byte[] content = transferProtocol.getContent();
        // 输出
        System.out.println("length=" + length);
        System.out.println("内容=:" + new String(content, StandardCharsets.UTF_8));
        System.out.println("接收的次数=" + (++count));
        // 回复数据
        String responseContent = UUID.randomUUID().toString().replaceAll("-", "");
        // 拿到长度
        int responseLength = responseContent.getBytes(StandardCharsets.UTF_8).length;
        // 构建消息
        TransferProtocol response = new TransferProtocol();
        response.setLength(responseLength);
        response.setContent(responseContent.getBytes(StandardCharsets.UTF_8));
        channelHandlerContext.writeAndFlush(response);
    }
}
